package org.destiny.swing.mapping.base;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.swing.JLabel;

import org.destiny.swing.annotation.FormItem;
import org.destiny.swing.mapping.FormItemMapper;

public abstract class AbstractFormItemMapper<T> implements FormItemMapper<T> {
	protected Field field;
	protected Class<?> fieldType;
	protected T fieldValue;
	protected FormItem formItem;
	protected Object model;
	protected Method getter, setter;

	public AbstractFormItemMapper(Field field) {
		this.field = field;
		this.fieldType = field.getType();
		this.formItem = field.getAnnotation(FormItem.class);

		try {
			PropertyDescriptor descriptor = new PropertyDescriptor(field.getName(), field.getDeclaringClass());
			getter = descriptor.getReadMethod();
			setter = descriptor.getWriteMethod();
		} catch (IntrospectionException e) {
			e.printStackTrace();
		}
	}

	@Override
	public Field getField() {
		return field;
	}

	@Override
	public JLabel getJLabel() {
		return new JLabel(formItem.label());
	}

	@Override
	public T getFieldValue() {
		return fieldValue;
	}

	@Override
	public void setFieldValue(T fieldValue) {
		try {
			setter.invoke(model, fieldValue);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		this.fieldValue = fieldValue;
	}
}
